package com.example.LibrarySystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.LibrarySystem.annotation.RoleAnnotation;
import com.example.LibrarySystem.mapper.PressesMapper;
import com.example.LibrarySystem.pojo.Preeses;
import com.example.LibrarySystem.response.Result;
import com.example.LibrarySystem.service.PreesesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/presses")
@Transactional // 事务管理
public class PressesController {

    @Autowired
    private PressesMapper pressesMapper;

    @Autowired
    private PreesesService preesesService;

    @PostMapping("/insert")
    @RoleAnnotation(type = "admin")
    public Result insert(@RequestBody Preeses preeses) {
        int res = pressesMapper.insert(preeses);

        if (res > 0) {
            return new Result("添加成功", 200);
        }
        return new Result("添加失败请重试", -1);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @RoleAnnotation(type = "admin")
    public Result deleteById(@PathVariable Integer id) {
        int res = pressesMapper.deleteById(id);
        if (res > 0) {
            return new Result("删除成功", 200);
        }
        return new Result("删除失败请重试", -1);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RoleAnnotation(type = "admin")
    public Result update(@RequestBody Preeses preeses) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",preeses.getId());
        int res = pressesMapper.update(preeses, queryWrapper);
        if (res > 0) {
            return new Result("修改成功", 200);
        }
        return new Result("修改失败请重试", -1);
    }

    /**
     * 根据name 进行模糊查询
     * @param name
     * @return
     */
    @GetMapping("/like")
    public Result likeByName(@RequestParam String name){
        List<Preeses> preeses = preesesService.likeByName(name);

        Result result = new Result();
        result.setStatus(200);
        result.put("data",preeses);
        result.setMsg("查询成功");
        return result;
    }
}
